/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.event;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.Cookie;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.EventBean;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.ReduceEventDynamicBean;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.bean.TreeData;
import com.sinodata.bsm.center.bean.WorkEnv;
import com.sinodata.bsm.center.cache.NewEventCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.utils.DateUtil;
import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.EventCauses;
import com.sinodata.bsm.common.vo.EventRemark;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author dongyushi
 * @version 1.0
 * 
 * <p>
 * History:
 * 
 * Date Author Version Description
 * ---------------------------------------------------------------------------------
 * 2012-5-29 上午9:51:16 dongyushi 1.0 To create
 * </p>
 * 
 * @since
 * @see
 */
public class ActiveEventAction extends BaseAction<Event> {

    /**
     * 
     */
    private static final long serialVersionUID = -1508700243446795699L;

    @Autowired
    private EventService eventService;

    @Autowired
    private NewEventCache newEventCache;

    public String common() {

        String format = "yyyyMMdd";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        String showFormat = "yyyy/MM/dd";
        SimpleDateFormat showSimple = new SimpleDateFormat(showFormat);
        List<ReduceEventDynamicBean> list = new ArrayList<ReduceEventDynamicBean>();
        String today = simple.format(new Date());
        String showToday = showSimple.format(new Date());
        ReduceEventDynamicBean todayData = eventService.getDynamicEvent(today, "D").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(today, "D").get(0);
        todayData.setTitle("今天" + "(" + showToday + ")");
        list.add(todayData);
        String yestoday = simple.format(new Date(new Date().getTime() - 3600000 * 24));
        ReduceEventDynamicBean yestodayData = eventService.getDynamicEvent(yestoday, "D").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(yestoday, "D").get(0);
        String showYestoday = showSimple.format(new Date(new Date().getTime() - 3600000 * 24));
        yestodayData.setTitle("昨天" + "(" + showYestoday + ")");
        list.add(yestodayData);

        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String week = simple.format(calendar.getTime());
        String showWeek1 = showSimple.format(calendar.getTime());
        String showWeek2 = showSimple.format(new Date(calendar.getTime().getTime() + 3600000 * 24 * 6));
        ReduceEventDynamicBean weekData = eventService.getDynamicEvent(week, "W").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(week, "W").get(0);
        weekData.setTitle("本周" + "(" + showWeek1 + "-" + showWeek2 + ")");
        list.add(weekData);

        String lastWeek = simple.format(new Date(calendar.getTime().getTime() - 3600000 * 24 * 7));
        String showLastWeek1 = showSimple.format(new Date(calendar.getTime().getTime() - 3600000 * 24 * 7));
        String showLastWeek2 = showSimple.format(new Date(calendar.getTime().getTime() - 3600000 * 24 * 1));
        ReduceEventDynamicBean LastWeekData = eventService.getDynamicEvent(lastWeek, "W").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(lastWeek, "W").get(0);
        LastWeekData.setTitle("上周" + "(" + showLastWeek1 + "-" + showLastWeek2 + ")");
        list.add(LastWeekData);

        String month = today.substring(0, 6);
        String showMonth = month.substring(0, 4) + "/" + month.substring(4, 6);
        ReduceEventDynamicBean monthData = eventService.getDynamicEvent(month, "M").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(month, "M").get(0);
        monthData.setTitle("本月" + "(" + showMonth + ")");
        list.add(monthData);

        Calendar calendar1 = Calendar.getInstance(Locale.CHINA);
        calendar1.add(Calendar.MONTH, -1);
        String lastMonth = simple.format(calendar1.getTime()).substring(0, 6);
        String showLastMonth = lastMonth.substring(0, 4) + "/" + lastMonth.substring(4, 6);
        ReduceEventDynamicBean lastMonthData = eventService.getDynamicEvent(lastMonth, "M").size() == 0 ? new ReduceEventDynamicBean() : eventService.getDynamicEvent(lastMonth, "M").get(0);
        lastMonthData.setTitle("上月" + "(" + showLastMonth + ")");
        list.add(lastMonthData);
        // 事件动态
        Struts2Utils.setRequestAttribute("viewData", list);
        // 统计信息
        // 当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        boolean showTotal = request.getParameter("showTotal") == null ? true : false;
        request.setAttribute("showTotal", showTotal);
        if (!showTotal) {
            //motiTypeId
            String motiTypeId = request.getParameter("motiTypeId");
            request.setAttribute("motiTypeId", motiTypeId);
        }
        if (resIds.toString() == null || resIds.toString().equals("")) {
            // 未认领
            Struts2Utils.setRequestAttribute("status0", "0");
            // 已认领
            Struts2Utils.setRequestAttribute("status1", "0");
            // 级别
            Struts2Utils.setRequestAttribute("level2", "0");
            Struts2Utils.setRequestAttribute("level3", "0");
            Struts2Utils.setRequestAttribute("level4", "0");
            Struts2Utils.setRequestAttribute("level5", "0");
            Struts2Utils.setRequestAttribute("allLevel", "0");
            return "common";
        }
        List<Object[]> listObject = new ArrayList<Object[]>();
        String userId = UserUtil.getInstance().getCurrentUserId();
        if (UserUtil.getInstance().isSysAdmin(userId) || UserUtil.getInstance().isGuest(userId)) { //guest用户有全部数据的查看权限
            listObject = eventService.getActiveEventNum(null);
        } else {
            listObject = eventService.getActiveEventNum(resIds.toString());
        }
        Object[] object = listObject.get(0);
        // 未认领
        Struts2Utils.setRequestAttribute("status0", object[0] == null ? "0" : String.valueOf(object[0]));
        // 已认领
        Struts2Utils.setRequestAttribute("status1", object[1] == null ? "0" : String.valueOf(object[1]));
        // 级别
        Struts2Utils.setRequestAttribute("level2", object[3] == null ? "0" : String.valueOf(object[3]));
        Struts2Utils.setRequestAttribute("level3", object[4] == null ? "0" : String.valueOf(object[4]));
        Struts2Utils.setRequestAttribute("level4", object[5] == null ? "0" : String.valueOf(object[5]));
        Struts2Utils.setRequestAttribute("level5", object[6] == null ? "0" : String.valueOf(object[6]));
        Struts2Utils.setRequestAttribute("allLevel", object[2] == null ? "0" : String.valueOf(object[2]));
        ///////////////////////////////////////////////////////////////////////////////////////////////////
        Cookie[] cookies = request.getCookies();
        Long lastTime = System.currentTimeMillis() - 3600 * 1000L;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(USER_AUDIO_LAST_TIME)) {
                lastTime = Long.parseLong(cookie.getValue());
                break;
            }
        }

        int level = SpringContextHolder.getBean(WorkEnv.class).getAudioEventLevel();
        Cookie mycook = new Cookie(USER_AUDIO_LAST_TIME, String.valueOf(System.currentTimeMillis()));
        mycook.setMaxAge(3600);
        response.addCookie(mycook);
        Date lastDate = new Date(lastTime);
        List<Event> events = eventService.getNewEvents(lastDate, level);
        List<Long> lastEventList = (List) request.getSession().getAttribute("lastEventList");
        if (lastEventList == null) {
            lastEventList = new ArrayList<Long>();
            request.setAttribute("lastEventList", lastEventList);
        }
        if (events.size() > 0) {
            lastEventList.clear();
            for (Event e : events) {
                //权限判断
                if (e.getLevel() > level) {
                    level = e.getLevel();
                }
                lastEventList.add(e.getId());
            }
        }

        boolean isPlay = false;
        String[] msgList = (String[]) request.getSession().getAttribute("msgList"); //new ArrayList<String>(3);
        if (msgList == null) {
            msgList = new String[3];
            request.getSession().setAttribute("msgList", msgList);

        }
        StringBuffer bf = new StringBuffer("");
        if (events.size() > 0) {
            isPlay = true;
            request.getSession().setAttribute("playTimes", "1");
            String str = DateUtil.format(lastDate, "HH:mm:ss") + " 至  " + DateUtil.format(new Date(), "HH:mm:ss") + " 产生 <font color='red'>" + events.size() + "</font> 条新事件。";
            msgList[0] = msgList[1];
            msgList[1] = msgList[2];
            msgList[2] = str;
            for (int i = msgList.length - 1; i >= 0; i--) {
                if (msgList[i] != null) {
                    bf.append(msgList[i]);
                }
                bf.append("<br>");
            }
        } else {
            String playTime = (String) request.getSession().getAttribute("playTimes");
            lastEventList = (List) request.getSession().getAttribute("lastEventList");
            if (playTime != null) {
                for (int i = 0; i < lastEventList.size(); i++) {
                    if (newEventCache.get(lastEventList.get(i)) != null) {
                        isPlay = true;
                        break;
                    }
                }
                lastEventList.clear();
                level = 0;
                request.getSession().removeAttribute("playTimes");
            }
        }
        request.getSession().setAttribute("lastEventList", lastEventList);
        //request.setAttribute("msg", bf.toString());
        request.setAttribute("isPlay", isPlay);
        request.setAttribute("maxLevel", level);
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        return "common";
    }

    private static final String USER_AUDIO_LAST_TIME = "userAudioLastTime";

    @Override
    public Event getModel() {
        return null;
    }

    @Override
    public String list() throws Exception {
        // 排序
        Map<String, String> orderMap = new HashMap<String, String>();
        String order = request.getParameter("sSortDir_0");
        String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
        if (!col.equals("checkbox")) {
            orderMap.put(tableColumsMap(col), order);
        }
        // 默认按时间降序
        if (orderMap.isEmpty()) {
            orderMap.put("e.OCCUR_TIME", "desc");
        }
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        String level = request.getParameter("level");
        String status = request.getParameter("status");
        // 当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        String userId = UserUtil.getInstance().getCurrentUserId();
        if (resIds.toString() != null && !resIds.toString().equals("")) {
            if (!UserUtil.getInstance().isSysAdmin(userId) && !UserUtil.getInstance().isGuest(userId)) {//guest用户有全部数据的查看权限
                map.put("resIds", resIds.toString());
            }
        } else {
            JSONObject json = new JSONObject();
            json.element("iTotalRecords", 0);
            json.element("iTotalDisplayRecords", 0);
            JSONArray array = new JSONArray();
            json.element("aaData", array);
            renderText(json.toString());
            return null;
        }
        if (level != null && !level.equals("")) {
            map.put("level_", level);
        }
        if (status != null && !status.equals("")) {
            map.put("status", status);
        } else {
            map.put("status", EventConstants.STATUS_NEW + "," + EventConstants.STATUS_ACKNOWLEDGED);
        }
        map.put("CATALOG", String.valueOf(EventConstants.CATALOG_FAULTEVENT));
        map.put("filter_event_id", null);
        ////////////////////////////////////////
        String motiTypeId = request.getParameter("motiTypeId");
        if (motiTypeId != null && !motiTypeId.equals("")) {
            map.put("motiTypeId", motiTypeId);
        }

        ///////////////////////////////////////
        condition.setWhere(map);
        Page<EventBean> page = new Page<EventBean>();
        page.setOrder(orderMap);
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        Page<EventBean> aaData = eventService.findEventByPage(page, condition, "");
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        for (EventBean eventBean : aaData.getRows()) {
            JSONObject obj = new JSONObject();
            obj.element("checkbox", "<div align='center'><input type='checkbox' name='dt_check' id='dt_check' value='" + eventBean.getEvent().getId() + "'></div>");
            if (eventBean.getEvent().getStatus() == EventConstants.STATUS_NEW) {
                obj.element("op", "<div style='width: 40px'>&nbsp;&nbsp;<a href='javascript:ack(" + eventBean.getEvent().getId() + ");'><img src='/bsm/style/default/bsm/images/ack.gif' title='认领'></a><div>");
            } else if (eventBean.getEvent().getStatus() == EventConstants.STATUS_ACKNOWLEDGED) {
                obj.element("op", "<div style='width: 40px'>&nbsp;&nbsp;<a href='javascript:confirm(" + eventBean.getEvent().getId() + ");'><img src='/bsm/style/default/bsm/images/confirm.gif' title='清除'></a><div>");
            }
            obj.element("id", eventBean.getEvent().getId());
            obj.element("ip", eventBean.getIp());
            Res parent = null;
            List<ResBean> resBeans = RelationHelper.parents(eventBean.getEvent().getResId());
            if (resBeans.size() > 0) {
                parent = resBeans.get(0).res();
            }
            StringBuffer parentNameValue = new StringBuffer("");
            parentNameValue.append(parent == null ? "" : parent.getName() + "/");
            parentNameValue.append(eventBean.getResName());
            obj.element("resName", parentNameValue.toString());
            obj.element("eventTypeName", eventBean.getEventTypeName());
            obj.element("msg", "<a href='/bsm/event/event-view!view.action?id=" + eventBean.getEvent().getId() + "' target='_blank'>" + eventBean.getEvent().getMsg() + "</a>");
            // 事件级别
            obj.element("level", eventBean.getEvent().getLevel());
            obj.element("levelName", "<div class='eventlevel" + eventBean.getEvent().getLevel() + "'></div>");
            obj.element("status", eventBean.getEvent().getStatus());
            obj.element("statusName", "<div class='status" + eventBean.getEvent().getStatus() + "'></div>");
            obj.element("occurTime", simple.format(eventBean.getEvent().getOccurTime()));
            obj.element("count", eventBean.getEvent().getCount() == null ? "" : eventBean.getEvent().getCount());
            obj.element("lastOccurTime", eventBean.getLastOccurTime() == null ? "" : eventBean.getLastOccurTime());
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String tooltipLevel() {
        Struts2Utils.setRequestAttribute("level", EventConstants.getLevelDesc(Integer.valueOf(request.getParameter("level"))));
        Struts2Utils.setRequestAttribute("status", "");
        Struts2Utils.setRequestAttribute("ack", "");
        Struts2Utils.setRequestAttribute("ackTime", "");
        return "tooltip";
    }

    public String tooltipStatus() {
        Struts2Utils.setRequestAttribute("level", "");
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        String eventId = request.getParameter("eventId");
        Event event = newEventCache.get(Long.valueOf(eventId));
        Struts2Utils.setRequestAttribute("ack", event.getAckUser() == null ? "" : (UserUtil.getInstance().getUserById(event.getAckUser()) == null ? event.getAckUser() + "此用户已删除" : UserUtil.getInstance().getUserById(event.getAckUser()).getFullName()));
        Struts2Utils.setRequestAttribute("ackTime", event.getAckTime() == null ? "" : simple.format(event.getAckTime()));
        Struts2Utils.setRequestAttribute("status", EventConstants.getStatusDesc(Integer.valueOf(request.getParameter("status"))));
        return "tooltip";
    }

    public String levelAndStatusData() {
        // 当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        Map<String, String> map = new HashMap<String, String>();
        if (resIds.toString() == null || resIds.toString().equals("")) {
            // 未认领
            map.put("status0", "0");
            // 已认领
            map.put("status1", "0");
            // 级别
            map.put("eventlevel2", "0");
            map.put("eventlevel3", "0");
            map.put("eventlevel4", "0");
            map.put("eventlevel5", "0");
            map.put("eventlevel", "0");
            Struts2Utils.renderJson(map);
            return null;
        }
        List<Object[]> listObject = new ArrayList<Object[]>();
        String userId = UserUtil.getInstance().getCurrentUserId();
        if (UserUtil.getInstance().isSysAdmin(userId) || UserUtil.getInstance().isGuest(userId)) { //guest用户有全部数据的查看权限
            listObject = eventService.getActiveEventNum(null);
        } else {
            listObject = eventService.getActiveEventNum(resIds.toString());
        }
        Object[] object = listObject.get(0);
        // 未认领
        map.put("status0", object[0] == null ? "0" : String.valueOf(object[0]));
        // 已认领
        map.put("status1", object[1] == null ? "0" : String.valueOf(object[1]));
        // 级别
        map.put("eventlevel2", object[3] == null ? "0" : String.valueOf(object[3]));
        map.put("eventlevel3", object[4] == null ? "0" : String.valueOf(object[4]));
        map.put("eventlevel4", object[5] == null ? "0" : String.valueOf(object[5]));
        map.put("eventlevel5", object[6] == null ? "0" : String.valueOf(object[6]));
        map.put("eventlevel", object[2] == null ? "0" : String.valueOf(object[2]));
        Struts2Utils.renderJson(map);
        return null;
    }

    public String ackDetails() {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        Long id = Long.parseLong(Struts2Utils.getParameter("id"));
        Event event = eventService.getEventById(id);
        Map<String, String> map = new HashMap<String, String>();
        map.put("ack", event.getAckUser() == null ? "" : UserUtil.getInstance().getUserById(event.getAckUser()).getFullName());
        map.put("ackTime", event.getAckTime() == null ? "" : simple.format(event.getAckTime()));
        map.put("lastOccurTime", event.getLastOccurTime() == null ? "" : simple.format(event.getLastOccurTime()));
        Struts2Utils.renderJson(map);
        return null;
    }

    @Override
    public String input() throws Exception {
        Struts2Utils.getRequest().setAttribute("id", request.getParameter("id"));
        return "batchack";
    }

    /**
     * 转向单条认领页面
     * 
     * @return
     * @throws Exception
     */
    public String singleAck() throws Exception {
        List<EventRemark> list = eventService.findEventRemarkByEventId(Long.valueOf(request.getParameter("id")));
        list = resultSort(list);
        // 为了前台显示 复用一下EventBean
        List<EventBean> listResult = new ArrayList<EventBean>();
        String format = "yyyy-MM-dd HH:mm";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        for (EventRemark eventRemark : list) {
            EventBean eventBean = new EventBean();
            eventBean.setAck(eventRemark.getUser());
            eventBean.setAckTime(simple.format(eventRemark.getTime()));
            eventBean.setResName(eventRemark.getRemarks());
            listResult.add(eventBean);
        }
        Struts2Utils.getRequest().setAttribute("id", request.getParameter("id"));
        Struts2Utils.getRequest().setAttribute("listResult", listResult);
        return "ack";
    }

    private List<EventRemark> resultSort(List<EventRemark> sortList) {
        for (int i = 0; i < sortList.size(); i++) {
            for (int j = 0; j < sortList.size() - i - 1; j++) {
                if (sortList.get(j).getTime().compareTo(sortList.get(j + 1).getTime()) > 0) {
                    EventRemark tmp = sortList.get(j);
                    sortList.set(j, sortList.get(j + 1));
                    sortList.set(j + 1, tmp);
                }
            }
        }
        return sortList;
    }

    public String ack() throws Exception {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        String ackUserId = UserUtil.getInstance().getCurrentUserId();
        Map<String, String> map = new HashMap<String, String>();
        // 校验事件是否已经被认领或者清除 (两个人同时操作的情况)
        if (id.contains(",")) {
            String[] ids = id.split(",");
            for (String eventId : ids) {
                Event event = newEventCache.get(Long.valueOf(eventId));
                if (event == null || !event.getStatus().equals(0)) {
                    map.put("flag", "false");
                    Struts2Utils.renderJson(map);
                    return null;
                }
            }
        } else {
            Event event = newEventCache.get(Long.valueOf(id));
            if (event == null || !event.getStatus().equals(0)) {
                map.put("flag", "false");
                Struts2Utils.renderJson(map);
                return null;
            }
        }

        // 批量认领
        if (id.contains(",")) {
            String[] array = id.split(",");
            Long[] ids = new Long[array.length];
            int i = 0;
            for (String str : array) {
                ids[i++] = Long.valueOf(str);
            }
            eventService.batchAck(ids, ackUserId, remarks);
        } else {
            eventService.ack(Long.valueOf(id), ackUserId, remarks);
            String format = "yyyy-MM-dd HH:mm";
            SimpleDateFormat simple = new SimpleDateFormat(format);
            map.put("user", UserUtil.getInstance().getUserById(ackUserId).getFullName());
            map.put("time", simple.format(new Date()));
        }
        map.put("flag", "true");
        Struts2Utils.renderJson(map);
        return null;
    }

    public String ackAndConfirm() throws Exception {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        String userId = UserUtil.getInstance().getCurrentUserId();
        Integer confirmType = EventConstants.CONFIRM_TYPE_USER;
        Map<String, String> map = new HashMap<String, String>();
        Event event = eventService.getEventById(Long.valueOf(id));
        if (!event.getStatus().equals(0)) {
            map.put("flag", "false");
            Struts2Utils.renderJson(map);
            return null;
        }
        // 先认领
        eventService.ack(Long.valueOf(id), userId, null);
        // 再清除
        eventService.confirm(Long.valueOf(id), confirmType, userId, null, remarks, true);
        map.put("flag", "true");
        Struts2Utils.renderJson(map);
        return null;
    }

    /**
     * 校验所选事件是否包含已被认领事件
     * 
     * @return
     * @throws Exception
     */
    public String ackCheck() throws Exception {
        String id = request.getParameter("id");
        String[] array = id.split(",");
        Long[] ids = new Long[array.length];
        int i = 0;
        for (String str : array) {
            ids[i++] = Long.valueOf(str);
        }
        Integer num = eventService.checkEventAck(ids);
        Integer num1 = eventService.checkEventConfirm(ids);
        if (num == 0 && num1 == 0) {
            renderText("true");
        }
        return null;
    }

    public String handelAuth() throws Exception {
        String eventIds = request.getParameter("id");
        String[] eventIdArray = eventIds.split(",");
        boolean flag = true;
        for (String eventId : eventIdArray) {
            if (!UserFunctionValidate.resFunctionValidate(eventService.getEventById(Long.valueOf(eventId)).getResId(), FunctionConstants.HANDLE_EVENT)) {
                flag = false;
                break;
            }
        }
        Struts2Utils.renderJson(flag);
        return null;
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        Struts2Utils.getRequest().setAttribute("id", request.getParameter("id"));
        return "batchconfirm";
    }

    /**
     * 转向单条清除页面
     * 
     * @return
     * @throws Exception
     */
    public String singleConfirm() throws Exception {
        Struts2Utils.getRequest().setAttribute("id", request.getParameter("id"));
        return "confirm";
    }

    public String remarksList() throws Exception {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        List<EventRemark> list = eventService.findEventRemarkByEventId(Long.valueOf(request.getParameter("id")));
        list = resultSort(list);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", list.size());
        json.element("iTotalDisplayRecords", list.size());
        JSONArray array = new JSONArray();
        for (EventRemark eventRemark : list) {
            JSONObject obj = new JSONObject();
            obj.element("time", simple.format(eventRemark.getTime()));
            obj.element("person", eventRemark.getUser());
            obj.element("remarks", eventRemark.getRemarks() == null ? "" : eventRemark.getRemarks());
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String confirmCheck() throws Exception {
        String id = request.getParameter("id");
        String[] array = id.split(",");
        Long[] ids = new Long[array.length];
        int i = 0;
        for (String str : array) {
            ids[i++] = Long.valueOf(str);
        }
        Integer num = eventService.checkEventConfirm(ids);
        if (num == 0) {
            renderText("true");
        }
        return null;
    }

    public String confirm() throws Exception {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        String cause = request.getParameter("cause");
        Integer confirmType = EventConstants.CONFIRM_TYPE_USER;
        String confirmUserId = UserUtil.getInstance().getCurrentUserId();
        Map<String, String> map = new HashMap<String, String>();
        // 校验事件是否已经被清除 (两个人同时操作的情况)
        if (id.contains(",")) {
            String[] ids = id.split(",");
            for (String eventId : ids) {
                Event event = newEventCache.get(Long.valueOf(eventId));
                if (event == null) {
                    map.put("flag", "false");
                    Struts2Utils.renderJson(map);
                    return null;
                }
            }
        } else {
            Event event = newEventCache.get(Long.valueOf(id));
            if (event == null) {
                map.put("flag", "false");
                Struts2Utils.renderJson(map);
                return null;
            }
        }

        // 批量清除
        if (id.contains(",")) {
            String[] array = id.split(",");
            Long[] ids = new Long[array.length];
            int i = 0;
            for (String str : array) {
                ids[i++] = Long.valueOf(str);
            }
            eventService.batchConfirm(ids, confirmType, confirmUserId, null, remarks, true);

            if (cause != null && !cause.equals("")) {
                for (Long eventId : ids) {
                    EventCauses eventCauses = new EventCauses();
                    eventCauses.setTitle(cause);
                    Event event = eventService.getEventById(eventId);
                    eventCauses.setEventId(event.getId());
                    eventCauses.setEventTypeId(event.getEventTypeId());
                    eventCauses.setResId(event.getResId());
                    eventService.addEventCauses(eventCauses);
                }
            }
        } else {
            eventService.confirm(Long.valueOf(id), confirmType, confirmUserId, null, remarks, true);
            if (cause != null && !cause.equals("")) {
                EventCauses eventCauses = new EventCauses();
                eventCauses.setTitle(cause);
                Event event = eventService.getEventById(Long.valueOf(id));
                eventCauses.setEventId(event.getId());
                eventCauses.setEventTypeId(event.getEventTypeId());
                eventCauses.setResId(event.getResId());
                eventService.addEventCauses(eventCauses);
            }
            EventBean eventBean = eventService.findInformationById(Long.valueOf(id));
            if (eventBean.getEvent().getConfirmType() != null && eventBean.getEvent().getConfirmType().equals(EventConstants.CONFIRM_TYPE_USER)) {
                map.put("userAck", eventBean.getEvent().getAckUser() == null ? " " : UserUtil.getInstance().getUserById(eventBean.getEvent().getAckUser()).getFullName());
                map.put("userConfirm", eventBean.getEvent().getConfirmer() == null ? " " : UserUtil.getInstance().getUserById(eventBean.getEvent().getConfirmer()).getFullName());
            } else {
                map.put("userAck", eventBean.getEvent().getAckUser() == null ? " " : "系统");
                map.put("userConfirm", eventBean.getEvent().getConfirmer() == null ? " " : "系统");
            }
            map.put("ackTime", eventBean.getAckTime() == null ? " " : eventBean.getAckTime());
            map.put("confirmTime", eventBean.getConfirmTime() == null ? " " : eventBean.getConfirmTime());
        }
        map.put("flag", "true");
        Struts2Utils.renderJson(map);
        return null;
    }

    /**
     * 跳转到我的视图中的 活动事件 页面
     * 
     * @return
     * @throws Exception
     */
    public String myevent() throws Exception {
        return "myevent";
    }

    @Override
    protected void prepareModel() throws Exception {

    }

    /**
     * 获得事件类型树 数据
     * 
     * @return
     * @throws IOException
     */
    public String eventTypeTreeData() throws IOException {
        String eventTypeId = request.getParameter("eventTypeId");
        List<TreeData> list = eventService.getEventTypeTreeData(eventTypeId);
        TreeData treeData = new TreeData();
        treeData.setId("-1");
        treeData.setName("资源类别");
        if (!eventTypeId.equals("-1")) {
            treeData.setChecked(true);
        }
        treeData.setChildren(list);
        JSONArray jSONArray = JSONArray.fromObject(treeData);
        renderText(jSONArray.toString());
        return null;
    }

    /**
     * 资源管理-资源信息 资源活动事件
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String resActiveEvents() {
        try {

            Long resId = Long.parseLong(Struts2Utils.getParameter("resId").toString());
            Page page = new Page();
            Enumeration<String> names = Struts2Utils.getRequest().getParameterNames();
            Map<String, String> parameterMap = new HashMap<String, String>();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                if (name.indexOf("FILTER") != -1) {
                    String value = Struts2Utils.getRequest().getParameter(name);
                    parameterMap.put(name.substring(name.indexOf("_") + 1), value);
                }
            }
            Condition condition = new Condition();
            condition.setWhere(parameterMap);
            int pageSize = Integer.parseInt(request.getParameter("iDisplayLength"));
            int start = Integer.parseInt(request.getParameter("iDisplayStart"));
            int pageno = (start / pageSize) + 1;
            page.setPageNo(pageno);
            page.setPageSize(pageSize);

            Map<String, Object> extensionParameter = new HashMap<String, Object>();
            extensionParameter.put("resId", resId);

            List<Object[]> listObject = eventService.getActiveEventNum(resId.toString());

            Object[] statuOb = listObject.get(0);

            JSONObject object = eventService.resActiveEventPage(page, condition, extensionParameter);
            object.element("claimOk", statuOb[1] == null ? 0 : statuOb[1]);
            object.element("claimNo", statuOb[0] == null ? 0 : statuOb[0]);
            object.element("level5", statuOb[6] == null ? 0 : statuOb[6]);
            object.element("level4", statuOb[5] == null ? 0 : statuOb[5]);
            object.element("level3", statuOb[4] == null ? 0 : statuOb[4]);
            object.element("level2", statuOb[3] == null ? 0 : statuOb[3]);
            object.element("allEvent", statuOb[2] == null ? 0 : statuOb[2]);
            Struts2Utils.renderText(object.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String tableColumsMap(String showName) {
        if (showName == null) {
            return null;
        }
        if (showName.equalsIgnoreCase("levelName")) {
            return "e.LEVEL_";
        } else if (showName.equalsIgnoreCase("eventTypeName")) {
            return "e.EVENT_TYPE_ID";
        } else if (showName.equalsIgnoreCase("occurTime")) {
            return "e.OCCUR_TIME";
        } else if (showName.equalsIgnoreCase("resName")) {
            return "r.NAME";
        }
        return showName;
    }
}
